package com.hntech.rpc.client;

import com.hntech.rpc.proxy.RpcRequest;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * @Autho changqi.wu
 * @Date 路在脚下，使劲踩！
 */
public class RpcTransport {

    private String host;
    private int port;

    public RpcTransport(String host, int port) {
        this.host = host;
        this.port = port;
    }

    private Socket newSocket(){
        System.out.println("开始新的链接");
        Socket socket = null;
        try {
            socket = new Socket(host,port);
        }catch (Exception e){
            e.printStackTrace();
        }
        return socket;
    }


    public Object send(RpcRequest request){

        ObjectInputStream objectInputStream = null;
        ObjectOutputStream outputStream = null;
        Socket socket = null;
        try {
            socket = newSocket();
            outputStream = new ObjectOutputStream(socket.getOutputStream());
            outputStream.writeObject(request);
            outputStream.flush();

            objectInputStream = new ObjectInputStream(socket.getInputStream());
            Object result = objectInputStream.readObject();

            outputStream.close();
            objectInputStream.close();

            return  result;

        } catch (Exception e) {

        } finally {
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }

}
